using UnityEngine;

public class Roller : MonoBehaviour
{
	public float angleLimit = 15f;

	public bool yoyoLoop;

	public float rotationSpeed = 10f;

	public float startDelay;

	private float currentAngle;

	private Quaternion inititalRotation;

	private bool isActive;

	private bool init = true;

	private float direction = 1f;

	private float startTime;

	private float myTime = -9999f;

	private void Awake()
	{
		LevelController.LevelReadyEvent += OnLevelReady;
		EventManager.WorldResetEvent += OnWorldReset;
		EventManager.GameFreezeEvent += OnGameFreeze;
		EventManager.GameUnfreezeEvent += OnGameUnfreeze;
	}

	private void OnDestroy()
	{
		LevelController.LevelReadyEvent -= OnLevelReady;
		EventManager.WorldResetEvent -= OnWorldReset;
		EventManager.GameFreezeEvent -= OnGameFreeze;
		EventManager.GameUnfreezeEvent -= OnGameUnfreeze;
	}

	private void OnLevelReady(Transform levelTransform)
	{
		if (base.transform.root == levelTransform)
		{
			isActive = true;
		}
	}

	private void OnWorldReset()
	{
		if (!base.GetComponent<Rigidbody>().isKinematic)
		{
			base.GetComponent<Rigidbody>().velocity = Vector3.zero;
			base.GetComponent<Rigidbody>().angularVelocity = Vector3.zero;
			base.GetComponent<Rigidbody>().isKinematic = true;
		}
		base.transform.rotation = inititalRotation;
		direction = 1f;
		init = true;
	}

	private void OnGameFreeze()
	{
		base.GetComponent<Rigidbody>().isKinematic = true;
	}

	private void OnGameUnfreeze()
	{
		base.GetComponent<Rigidbody>().isKinematic = false;
	}

	private void FixedUpdate()
	{
		if (Time.fixedDeltaTime < 0.001f)
		{
			return;
		}
		if (myTime == -9999f)
		{
			myTime = 0f - Time.fixedDeltaTime;
		}
		myTime += Time.fixedDeltaTime;
		if (!isActive)
		{
			return;
		}
		if (init)
		{
			Initialize();
			init = false;
		}
		if (init || !(myTime - startTime >= startDelay))
		{
			return;
		}
		float num = Time.fixedDeltaTime * rotationSpeed * direction;
		currentAngle += num;
		if (yoyoLoop)
		{
			if (currentAngle > angleLimit && direction > 0f)
			{
				direction *= -1f;
			}
			if (currentAngle < 0f - angleLimit && direction < 0f)
			{
				direction *= -1f;
			}
		}
		base.GetComponent<Rigidbody>().MoveRotation(Quaternion.Euler(base.transform.TransformDirection(num * Vector3.down)) * base.transform.rotation);
	}

	private void Initialize()
	{
		inititalRotation = base.transform.localRotation;
		currentAngle = 0f;
		startTime = myTime;
		base.GetComponent<Rigidbody>().isKinematic = true;
	}
}
